# -*- coding: utf-8 -*-
"""
author:码同学 极光
date:9
desc: 
sample: 
"""
import json

from apitest.models import TestCase, EnvInfo, TestApiResult
from application.celery import app
from dvadmin.utils.RequestUtil import RequestUtil


@app.task
def apiTask(**kwargs):
    print(kwargs)
    case_id = kwargs.get('case_id')
    env_id = kwargs.get('evn_id')
    testcase = TestCase.objects.get(id=case_id)
    if testcase:
        apis = testcase.apis.all()
        api = RequestUtil()
        env = EnvInfo.objects.get(id=env_id)
        if env is not None:
            paramsbody = env.paramsbody
            if paramsbody is not None and paramsbody != '':
                api.var_pool_data = json.loads(paramsbody)
        for apiinfo in apis:
            url = apiinfo.url
            headers = apiinfo.headers
            verification = apiinfo.verification
            extract = apiinfo.extract

            if apiinfo.params_type == 1:
                # 数据格式 data  id=1&name=test
                params_dic = {}
                if apiinfo.params is not None and apiinfo.params != '':
                    for item in apiinfo.params.split("&"):
                        k = item.split("=")[0]
                        v = item.split("=")[1]
                        params_dic[k] = v
                api.send_request(apiinfo.get_method_display(), url,
                                 verification=verification, case_desc=apiinfo.description,
                                 headers=headers, data=params_dic, extract=extract)
            elif apiinfo.params_type == 2:
                api.send_request(apiinfo.get_method_display(), url,
                                 verification=verification, case_desc=apiinfo.description,
                                 headers=headers, json=apiinfo.jsonbody, extract=extract)
            else:
                api.send_request(apiinfo.get_method_display(), url,
                                 verification=verification, case_desc=apiinfo.description,
                                 headers=headers, extract=extract)

            print("测试结果")
            print(api.get_result())
            # 返回结果有异常
            # if api.get_result().get('code') == 0:
            #     return ErrorResponse(msg=api.get_result().get('response'))
            # 写数据库 insert  orm
            testApiResult = TestApiResult()
            testApiResult.case_belong = testcase
            testApiResult.api_belong = apiinfo
            testApiResult.project_belong = apiinfo.project_belong
            testApiResult.module_belong = apiinfo.module_belong
            testApiResult.took_time = api.get_result().get("took_time")
            testApiResult.env_belong = env
            result = api.get_result().get("response")
            if len(result) > 200:
                result = result[0:200]
            testApiResult.result = result
            testApiResult.verification = api.get_result().get("check_result")
            testApiResult.save()
            print("数据保存到数据库了")